package com.weiyuanstudio.nextstep.controller;

import com.weiyuanstudio.nextstep.persistence.entity.BangumiCollection;
import com.weiyuanstudio.nextstep.persistence.repository.BangumiCollectionRepository;
import com.weiyuanstudio.nextstep.thirdparty.api.BangumiCollectionDTO;
import com.weiyuanstudio.nextstep.thirdparty.api.bangumi.UserCollectionAPI;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/test")
public class TestController {
    UserCollectionAPI userCollectionAPI;
    BangumiCollectionRepository bangumiCollectionRepository;

    public TestController(UserCollectionAPI userCollectionAPI, BangumiCollectionRepository bangumiCollectionRepository) {
        this.userCollectionAPI = userCollectionAPI;
        this.bangumiCollectionRepository = bangumiCollectionRepository;
    }

    @GetMapping("/test1")
    public List<BangumiCollectionDTO> allUser() {
        try {
            List<BangumiCollectionDTO> data = userCollectionAPI.getUserAllCollection("weiyuan"); //爬取当前用户所有信息

            List<BangumiCollection> entityList = convertBangumiToEntity(data); //转换DTO成Entity待存库

            bangumiCollectionRepository.saveAll(entityList); //存库

            System.out.println("data.size() = " + data.size());
            return data;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/ping")
    public String ping() {
        return "pong";
    }

    public List<BangumiCollection> convertBangumiToEntity(List<BangumiCollectionDTO> bangumiCollectionDTOList) {
        List<BangumiCollection> temp = new ArrayList<>();

        if (bangumiCollectionDTOList == null) return temp;

        for (BangumiCollectionDTO dto : bangumiCollectionDTOList) {
            BangumiCollection entity = new BangumiCollection();
            BeanUtils.copyProperties(dto, entity);
            temp.add(entity);
        }

        return temp;
    }
}
